package com.itcam.lease.web.admin.service.impl;

import com.itcam.lease.common.constant.RedisConstant;
import com.itcam.lease.common.exception.LeaseException;
import com.itcam.lease.common.result.ResultCodeEnum;

import com.itcam.lease.common.utils.JWTUtil;
import com.itcam.lease.model.entity.SystemUser;
import com.itcam.lease.model.enums.BaseStatus;
import com.itcam.lease.web.admin.mapper.SystemUserMapper;
import com.itcam.lease.web.admin.service.LoginService;
import com.itcam.lease.web.admin.vo.login.CaptchaVo;
import com.itcam.lease.web.admin.vo.login.LoginVo;
import com.itcam.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.minio.Digest;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings("all")
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取图形验证码
     * @return
     */
    @Override
    public CaptchaVo getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        String code = specCaptcha.text().toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        String image = specCaptcha.toBase64();
        redisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        return new CaptchaVo(image, key);
    }

    /**
     * 登录
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {
        // 1. 判断是否输入了验证码
        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
            // 如果未输入验证码，抛出异常
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        // 2. 校验验证码
        String code = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code == null) {
            // 如果验证码已过期，抛出异常
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())) {
            // 如果验证码不正确，抛出异常
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        // 3. 校验用户是否存在
        SystemUser systemUser = systemUserMapper.selectOneByUsername(loginVo.getUsername());
        if (systemUser == null) {
            // 如果用户不存在，抛出异常
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        // 4. 校验用户是否被禁
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            // 如果用户被禁用，抛出异常
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        // 5. 校验用户密码
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            // 如果密码不正确，抛出异常
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        // 6. 创建并返回TOKEN
        return JWTUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }

    /**
     * 获取登陆用户个人信息
     *
     * @param userId 用户ID
     * @return 返回包含用户个人信息的响应
     */
    @Override
    public SystemUserInfoVo getLoginUserInfo(Long userId) {
        // 根据用户ID查询用户信息
        SystemUser systemUser = systemUserMapper.selectById(userId);
        // 创建一个新的 SystemUserInfoVo 对象
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        // 将用户的姓名设置到 SystemUserInfoVo 对象中
        systemUserInfoVo.setName(systemUser.getName());
        // 将用户的头像URL设置到 SystemUserInfoVo 对象中
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        // 返回包含用户个人信息的 SystemUserInfoVo 对象
        return systemUserInfoVo;
    }


}
